//
//  CTPDetailListViewController.m
//  LittleNotes
//
//  Created by 檀志文 on 16/5/19.
//  Copyright © 2016年 ios檀志文. All rights reserved.
//

#import "CTPDetailListViewController.h"
#import "UIBarButtonItem+Extension.h"
#import "DWBubbleMenuButton.h"
#import "XXXRoundMenuButton.h"
#import "CTPComposeViewController.h"
#import "CTPNavViewController.h"
#import "CTPDetailTextTableViewCell.h"
#import "CTPMsgViewModel.h"
#pragma mark - 新增类
#import "MenuView.h"
#import <Masonry.h>
#import "NoteDetails.h"
#import "EditTVC.h"
#import "UIImage+Enlarge.h"
#import <HMAlbum.h>
#import "HMImagePickerController.h"
#import "PhotoPickerCell.h"
#import "SoundController.h"
@interface CTPDetailListViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, HMImagePickerControllerDelegate>
@property(nonatomic, copy) NSString *navTitle;
/**
 *  记事本菜单
 */
@property(nonatomic,strong) MenuView *menuView;
/**
 * 标题按钮
 */
@property(nonatomic,strong) UIButton *titleBtn;
/**
 *  获得主窗口
 */
@property(nonatomic,strong) UIWindow *window;
/**
 *  遮盖按钮
 */
@property(nonatomic,strong) UIButton *coverBtn;
/**
 *  存储选择图片的数组
 */
@property(nonatomic,strong) NSMutableArray<UIImage *> *images;
@property(nonatomic,strong) NSMutableArray<PHAsset *> *selectedAssets;
/**
 *  展示图片的collectionView
 */
@property(nonatomic, weak) IBOutlet UICollectionView *collectionView;
/**
 *  layout
 */
@property(nonatomic,strong) IBOutlet UICollectionViewFlowLayout *layout;
/**
 *  相片选择器
 */
@property(nonatomic,strong) HMImagePickerController *picker;
/*#########################################################*/
// 时间选择
@property (nonatomic, strong) UILabel *label;
// 发布选择
@property (nonatomic, strong) UILabel *labelType;

@property (nonatomic, strong) XXXRoundMenuButton *button2;

//messages的模型数组
@property (nonatomic, strong) NSMutableArray *messages;

@end

@implementation CTPDetailListViewController

// view已经显示的时候加载


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
        [self refreshDatas];
}
- (void)viewDidAppear:(BOOL)animated {
    
    // Create down menu button
    UILabel *homeLabel = [self createHomeButtonView1];
    
    DWBubbleMenuButton *upMenuView = [[DWBubbleMenuButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width - homeLabel.frame.size.width - 20.f,
                                                                                          self.view.frame.size.height - homeLabel.frame.size.height - 20.f,
                                                                                          homeLabel.frame.size.width,
                                                                                          homeLabel.frame.size.height)
                                                            expansionDirection:DirectionDown];
    upMenuView.homeButtonView = homeLabel;
    
    [upMenuView addButtons:[self createDemoButtonArray:0]];
    
    self.navigationItem.title = @"列表";
    //    设置一个自定义按钮
    UIBarButtonItem *sLeftBarButton = [[UIBarButtonItem alloc]initWithCustomView:upMenuView];
    UIButton *button = [[UIButton alloc]init];
    button.frame = CGRectMake(0, 0, 22, 22);
    [button setBackgroundImage:[UIImage imageNamed:@"Search"] forState:UIControlStateNormal];
    //    设置一个自定义按钮
    UIBarButtonItem *sRightBarButton = [[UIBarButtonItem alloc]initWithCustomView:button];
    //   设置导航栏按钮
    self.navigationItem.leftBarButtonItems =@[sLeftBarButton,sRightBarButton];
    
//  去发布语音或者文字/图片说说
    homeLabel = [self createHomeButtonView2];
    DWBubbleMenuButton *downMenuButton = [[DWBubbleMenuButton alloc] initWithFrame:CGRectMake(20.f,20.f,homeLabel.frame.size.width,homeLabel.frame.size.height)
                                                                expansionDirection:DirectionLeft];
    downMenuButton.homeButtonView = homeLabel;
    
    [downMenuButton addButtons:[self createDemoButtonArray:1]];

    //    设置一个自定义按钮
    UIBarButtonItem *chooseBarButton = [[UIBarButtonItem alloc]initWithCustomView:downMenuButton];
    self.navigationItem.rightBarButtonItem = chooseBarButton;
}

#pragma mark - 查询按钮的设置
- (UILabel *)createHomeButtonView1 {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0.f, 0.f, 45.f, 45.f)];
    label.text = @"请选择";
    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.layer.cornerRadius = label.frame.size.height / 2.f;
    label.backgroundColor = CMTGlobalColor;
    label.alpha = 0.5;
    label.font = [UIFont systemFontOfSize:10];
    label.clipsToBounds = YES;
    self.label =label;
    return label;
}
- (UILabel *)createHomeButtonView2 {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0.f, 0.f, 45.f, 45.f)];
    label.text = @"请选择";
    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.layer.cornerRadius = label.frame.size.height / 2.f;
    label.backgroundColor = CMTGlobalColor;
    label.alpha = 0.5;
    label.font = [UIFont systemFontOfSize:10];
    label.clipsToBounds = YES;
        self.labelType=label;
    return label;
}

- (NSArray *)createDemoButtonArray:(NSInteger)type {
    
    NSMutableArray *buttonsMutable = [[NSMutableArray alloc] init];
    int i = 0;
//  判断类型，到底是否什么类型
    NSArray *dicArr=type ==0?@[@"本周", @"本月", @"一个月前"]:@[@"语音",@"文字/图片"];
    for (NSString *title in dicArr) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button setTitle:title forState:UIControlStateNormal];
        
        button.frame = CGRectMake(0.f, 0.f, 45.f, 45.f);
        button.layer.cornerRadius = button.frame.size.height / 2.f;
        button.backgroundColor = CMTGlobalColor;
        button.clipsToBounds = YES;
        button.titleLabel.font=[UIFont systemFontOfSize:10];
        button.alpha=0.5;
        button.tag = i++;
        if (type==0) {
            [button addTarget:self action:@selector(searchByCondition:) forControlEvents:UIControlEventTouchUpInside];
        }else{
            [button addTarget:self action:@selector(composeType:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        
        [buttonsMutable addObject:button];
    }
    return [buttonsMutable copy];
}

- (UIButton *)createButtonWithName:(NSString *)imageName {
    
    
    UIButton *button = [[UIButton alloc] init];
    [button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [button sizeToFit];
    
    [button addTarget:self action:@selector(searchByCondition:) forControlEvents:UIControlEventTouchUpInside];
    
    return button;
}

#pragma mark 根据年月日(查询)设置查询条件

- (void)searchByCondition:(UIButton *)sender {
    
//  根据查询条件查询相应的记事本
    
    self.label.text = sender.titleLabel.text;
    NSLog(@"Button tapped, tag: %ld", (long)sender.titleLabel.text);
}

#pragma mark 发布笔记的方式
-(void)composeType:(UIButton *)sender{
    //  调用方法跳转到发布说说或者语音界面
    if ([sender.titleLabel.text isEqualToString:@"语音"]) {
        [self.navigationController pushViewController:[[SoundController alloc] init] animated:YES];
    } else {
        [self.navigationController pushViewController:[[CTPComposeViewController alloc] init] animated:YES];
    }
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.tableView registerNib:[UINib nibWithNibName:@"CTPDetailTextTableViewCell" bundle:nil] forCellReuseIdentifier:@"text"];
    self.tableView.rowHeight= 100;
    self.view.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
    
    [self setupTitleView];
    [self setupCollection];
}

#pragma mark- 刷新数据
-(void) refreshDatas{
    //  1 先从缓存找
    //  2 没找到就去数据库中找
    _messages=[[CTPMsgViewModel sharedMsgInstance] searchAllMsgs];
    
    [self.tableView reloadData];
}


#pragma mark - 选择发布语音或者是文本/图片
-(void) didChooseYuYinOrTextImage{

}


#pragma mark - TableView 的数据源和代理方法


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.messages.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CTPDetailTextTableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:@"text" forIndexPath:indexPath];
    cell.message = self.messages[indexPath.row];
    
    return cell;
}

#pragma mark - 代理方法
//- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath{
//    return NO;
//}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"123");
}

#pragma mark - 懒加载
- (UILabel *)label{
    if (_label == nil) {
        _label = [[UILabel alloc] init];
    }
    return _label;
}
- (UILabel *)labelType{
    if (_labelType == nil) {
        _labelType = [[UILabel alloc] init];
    }
    return _labelType;
}

- (XXXRoundMenuButton *)button2{
    if (_button2 == nil) {
        _button2 = [[XXXRoundMenuButton alloc] init];
    }
    return _button2;
}

- (NSMutableArray *)messages{
    if (_messages == nil) {
        _messages = [[[CTPMsgViewModel sharedMsgInstance]searchAllMsgs] copy];
        ;
    }
    return _messages;
}
#pragma mark - 新增方法
- (void)didClickAddBtn {
    self.picker = [[HMImagePickerController alloc] initWithSelectedAssets:self.selectedAssets];
    self.picker.pickerDelegate = self;
    // 设置目标图片尺寸
    self.picker.targetSize = CGSizeMake(600, 600);
    // 设置最大选择照片的数量
    self.picker.maxPickerCount = 9;
    // 进入选择照片控制器
    [self presentViewController:self.picker animated:YES completion:nil];
}
- (void)didClickDeleteBtn:(PhotoPickerCell *)cell {
    // 移除对象
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
    [self.images removeObjectAtIndex:indexPath.item];
    [self.selectedAssets removeObjectAtIndex:indexPath.item];
    // 刷新选择
    [self.collectionView reloadData];
}

#pragma mark - 实现黑马选择器的代理
- (void)imagePickerController:(HMImagePickerController *)picker didFinishSelectedImages:(NSArray<UIImage *> *)images selectedAssets:(NSArray<PHAsset *> *)selectedAssets {
    // 获得的图片
    [self.images addObjectsFromArray:images];
    // 已经选择的图片
    [self.selectedAssets addObjectsFromArray:selectedAssets];
    // 退出照片选择器
    [self.picker dismissViewControllerAnimated:YES completion:nil];
    // 刷新显示
    [self.collectionView reloadData];
}
#pragma mark - collectionView
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    // 返回比选择的照片多一个
    CGFloat count = self.images.count != 0 ? self.images.count + 1 : 1;
    if (self.images.count == 0) {
        count = 1;
    } else if (self.images.count < 9) {
        count = self.images.count + 1;
    } else {
        count = 9;
    }
    return count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    PhotoPickerCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"photos" forIndexPath:indexPath];
    // 传递图片
    if (indexPath.item < self.images.count) {
        cell.image = self.images[indexPath.item];
    } else {
        [cell showAddBtn];
    }
    // 删除选择的图片
    __weak typeof(cell) weakCell = cell;
    [cell setDeleteImagesBlock:^{
        [self didClickDeleteBtn:weakCell];
    }];
    // 选择图片
    [cell setPickerImagesBlock:^{
        [self didClickAddBtn];
    }];
    return cell;
}
- (void)setupCollection {
    // 设置背景
    self.collectionView.backgroundColor = [UIColor whiteColor];
    // 指定数据源额代理
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    // 设置layout
    self.layout.itemSize = CGSizeMake(80, 80);
    // 注册
    [self.collectionView registerClass:[PhotoPickerCell class] forCellWithReuseIdentifier:@"photos"];
    // 设置基本间距
    self.collectionView.contentInset = UIEdgeInsetsMake(10, 10, 10, 10);
}
- (void)setupTitleView {
    // 准备图片
    UIImage *titleImg = [UIImage imageNamed:@"CategoryTop"];
    // 准备按钮
    UIButton *btn = [[UIButton alloc] init];
    [btn setImage:titleImg forState:UIControlStateNormal];
    [btn setTitle:self.navTitle forState:UIControlStateNormal];
    // 准备基本间距数据
    CGFloat leftInset = self.navTitle.length * 10;
    // 设置图片内间距
    [btn setImageEdgeInsets:UIEdgeInsetsMake(0, leftInset * 3, 0, 0)];
    // 设置文字内间距
    [btn setTitleEdgeInsets:UIEdgeInsetsMake(0, -leftInset, 0, 0)];
    // 监听按钮点击
    [btn addTarget:self action:@selector(didClickTitlteBtn:) forControlEvents:UIControlEventTouchUpInside];
    btn.frame = CGRectMake(0, 0, leftInset * 4, 30);
    //    [btn setBackgroundColor:[UIColor blueColor]];
    self.navigationItem.titleView = btn;
    self.titleBtn = btn;
}
// 监听标题按钮的点击
- (void)didClickTitlteBtn:(UIButton *)btn {
    if (!btn.selected) {
        // 动画旋转标题三角图片
        [UIView animateWithDuration:0.25 animations:^{
            btn.imageView.transform = CGAffineTransformMakeRotation(M_PI);
        }];
        // 获得主窗口
        self.window = [UIApplication sharedApplication].keyWindow;
        // 添加遮罩按钮
        [self.window addSubview:self.coverBtn];
        // 显示记事本菜单
        [self.window addSubview:self.menuView];
        // 设置约束
        [self.menuView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.top.equalTo(self.view).offset(-10);
            make.height.mas_equalTo(400);
            make.width.mas_equalTo(200);
        }];
        // 设置反选
        btn.selected = !btn.selected;
    } else {
        [self removiewMenuView];
    }
}
- (void)removiewMenuView {
    // 动画回复三角图标
    [UIView animateWithDuration:0.25 animations:^{
        self.titleBtn.imageView.transform = CGAffineTransformIdentity;
    }];
    // 移除记事本菜单
    [self.menuView removeFromSuperview];
    // 回复标题按钮的选择状态
    self.titleBtn.selected = !self.titleBtn.selected;
}
// 监听记事本菜单消失
- (void)dismissMenuView {
    [self removiewMenuView];
    [self.coverBtn removeFromSuperview];
    [self.window removeFromSuperview];
}
#pragma mark - 懒加载
- (NSMutableArray<UIImage *> *)images {
    if (_images == nil) {
        _images = [NSMutableArray array];
    }
    return _images;
}
- (NSMutableArray<PHAsset *> *)selectedAssets {
    if (_selectedAssets == nil) {
        _selectedAssets = [NSMutableArray array];
    }
    return _selectedAssets;
}
- (MenuView *)menuView {
    if (_menuView == nil) {
        _menuView = [MenuView menuView];
        __weak typeof(self) weakVC = self;
        [_menuView setJumpToVCFromCell:^{
            // 切换主View
            weakVC.view = [[NoteDetails alloc] init];
            // 移除菜单View,回复三角图标的状态
            [weakVC removiewMenuView];
            // 传递标题
        }];
        [_menuView setJumpToVCFromEdit:^{
            // 移除菜单View,回复三角图标的状态
            [weakVC removiewMenuView];
            // 跳转控制器
            EditTVC *vc = [[EditTVC alloc] init];
            vc.title = @"编辑分类";
            [weakVC.navigationController pushViewController:vc animated:YES];
        }];
    }
    return _menuView;
}
- (UIButton *)coverBtn {
    if (_coverBtn == nil) {
        _coverBtn = [[UIButton alloc] init];
        [_coverBtn setBackgroundColor:[UIColor clearColor]];
        _coverBtn.frame = CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 64);
        [_coverBtn addTarget:self action:@selector(dismissMenuView) forControlEvents:UIControlEventTouchUpInside];
    }
    return _coverBtn;
}
@end
